import { PermissionState } from '@/types/store/permission';  //基本形状
import { RouteRecordRaw } from 'vue-router';  //路由列表实体
import { defineStore } from 'pinia';  //pinia创建stroe的方法
import { constantRoutes } from '@/router';  //路由里的方法？这是哪个？
import { listRoutes } from '@/api/system/menu';  //获得所有路由的api

const modules = import.meta.glob('../../views/**/**.vue');  //获得所有的views组件？
export const Layout = () => import('@/layout/index.vue');  //获得布局组件

//判断路由和角色之间是否存在关系
const hasPermission = (roles: string[], route: RouteRecordRaw) => {
  console.log(route.meta && route.meta.roles)
  if (route.meta && route.meta.roles) {
    if (roles.includes('ROOT')) {
      return true;
    }
    return roles.some((role) => {
      if (route.meta?.roles !== undefined) {
        return (route.meta.roles as string[]).includes(role);
      }
    });
  }
  return false;
};
//根据角色过滤路由
export const filterAsyncRoutes = (
  routes: RouteRecordRaw[],
  roles: string[]
) => {
  const res: RouteRecordRaw[] = [];
  routes.forEach((route) => {
    const tmp = { ...route } as any;
    if (hasPermission(roles, tmp)) {
      if (tmp.component == 'Layout') {
        tmp.component = Layout;
      } else {
        const component = modules[`../../views/${tmp.component}.vue`] as any;
        if (component) {
          tmp.component = modules[`../../views/${tmp.component}.vue`];
        } else {
          tmp.component = modules[`../../views/error-page/404.vue`];
        }
      }
      res.push(tmp);

      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles);
      }
    }
  });
  return res;
};

//定义好的存储位置
const usePermissionStore = defineStore({
  id: 'permission',
  state: (): PermissionState => ({
    routes: [],
    addRoutes: [],
  }),
  actions: {
    //设置路由的方法
    setRoutes(routes: RouteRecordRaw[]) {
      this.addRoutes = routes;   //路由存储下来
      this.routes = constantRoutes.concat(routes);
    },
    //获取路由的方法
    generateRoutes(roles: string[]) {
      return new Promise((resolve, reject) => {
        listRoutes()
          .then((response) => {
            const asyncRoutes = response.data;
            console.log("我看看路由");
            console.log(asyncRoutes)
            console.log(roles);
            const accessedRoutes = filterAsyncRoutes(asyncRoutes, roles);
            console.log("处理过后的路由")
            console.log(accessedRoutes);
            this.setRoutes(accessedRoutes);   //设置路由，还把路由保存在steta中
            resolve(accessedRoutes);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
  },
});

export default usePermissionStore;
